package com.xqyq.controller.manage;

import java.sql.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xqyq.model.Report;
import com.xqyq.model.ReportContent;
import com.xqyq.service.ReportService;
import com.xqyq.util.CommonUtil;
@RequestMapping("/manage")
@Controller
public class SysReportContorller {

	@Autowired
	private ReportService reportService;

	@RequestMapping("/report.html")
	public String report(HttpServletRequest request) {
		List<Report> reportList = reportService.getAllReport();
		request.setAttribute("reportList", reportList);
		return "manage/report";
	}

	@RequestMapping("/report_edit.html")
	public String reportEdit(HttpServletRequest request) {
		if (request.getParameter("report_id") != null) {
			Report report = reportService.getTheWholeReport(Integer
					.parseInt(request.getParameter("report_id")));
			request.setAttribute("report", report);
		}
		return "manage/report_edit";
	}

	@RequestMapping(value = "/api_editReport", method = RequestMethod.POST)
	@ResponseBody
	public String editReport(Report report, ReportContent report_content,
			HttpServletRequest request) {
		if (CommonUtil.isEmpty(report.getCover())
				|| CommonUtil.isEmpty(report.getReport_name())
				|| CommonUtil.isEmpty(report_content.getContent())) {
			return "{\"state\":104,\"comment\":\"请填写完整信息。\"}";
		} else {
			report.setReport_content(report_content);
			report_content.setReport(report);
			report.setDate(new Date(System.currentTimeMillis()));
			if (request.getParameter("report_id") == null) {
				if (reportService.addReport(report) == true) {
					return "{\"state\":200,\"comment\":\"保存成功。\"}";
				} else {
					return "{\"state\":104,\"comment\":\"保存失败，请检查是否重复添加同一新闻。\"}";
				}
			} else {
				System.out.println(report_content.getContent());
				reportService.updateReport(report);
				return "{\"state\":200,\"comment\":\"保存成功。\"}";
			}
		}
	}

	@RequestMapping("/api_deleteReport")
	public String deleteReport(@RequestParam("report_id") int report_id) {
		reportService.deleteReport(report_id);
		return "redirect:report.html";
	}

}
